﻿using DevExpress.XtraEditors;
using MixingStation.LTWebService;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MixingStation
{
    public partial class PurchaseOrderSelectForm : Form
    {
        //绑定table 
        private DataTable m_BindDT;

        private materialWS[] m_MaterialArr = null;
        public materialWS[] MaterialArr
        {
            set
            {
                m_MaterialArr = value;
            }
        }

        private supplierWS[] m_SupplierArr = null;
        public supplierWS[] SupplierArr
        {
            set
            {
                m_SupplierArr = value;
            }
        }

        private purchaseOrderWS m_SelectPurchaseOrder = null;
        public purchaseOrderWS SelectPurchaseOrder
        {
            get
            {
                return m_SelectPurchaseOrder;
            }
        }

        private Dictionary<long, purchaseOrderWS> m_PurchaseOrderDic = new Dictionary<long, purchaseOrderWS>();

        //当前选择的物料Id
        private long m_CurrentMaterialId = 0;
        //当前选择的供应商Id
        private long m_CurrentSupplierId = 0;
        //当前的订单编号
        private string m_CurrentOrderCode = "";
        public PurchaseOrderSelectForm()
        {
            InitializeComponent();
        }

        //传入物料编码
        private string m_MaterialCode = "";
        public string MaterialCode
        {
            set
            {
                m_MaterialCode = value;
            }
        }

        //传入供应商编码
        private string m_SupplierCode = "";
        public string SupplierCode
        {
            set
            {
                m_SupplierCode = value;
            }
        }

        private void PurchaseOrderSelectForm_Load(object sender, EventArgs e)
        {
            InitBindDT();
            InitMaterialCombox();
            IniSupplierCombox();
            //根据传入的物料编码和供应商编码初始化选择项
            if(!string.IsNullOrEmpty(m_MaterialCode))
                cmbMaterial.SelectedItem = FindMaterialDataInfoByKey(cmbMaterial, m_MaterialCode);
            if (!string.IsNullOrEmpty(m_SupplierCode))
                cmbSupplier.SelectedItem = FindSupplierDataInfoByKey(cmbSupplier, m_SupplierCode);
            Search();
        }

        #region 私有方法
        private void InitBindDT()
        {
            m_BindDT = new DataTable();
            m_BindDT.Columns.Add("id");
            m_BindDT.Columns.Add("Material");
            m_BindDT.Columns.Add("Supplier");
            m_BindDT.Columns.Add("Place");
            m_BindDT.Columns.Add("OrderCode");
            m_BindDT.Columns.Add("OrderNum");
            m_BindDT.Columns.Add("ReceNum");
            m_BindDT.Columns.Add("OrderTime");
            this.gridOrder.DataSource = m_BindDT;
        }

        private void InitMaterialCombox()
        {
            if (m_MaterialArr == null || m_MaterialArr.Length == 0)
                return;
            var list = new List<MaterialDataInfo>();
            list.Add(new MaterialDataInfo { Code = "", Value = null });
            foreach (materialWS material in m_MaterialArr)
                list.Add(new MaterialDataInfo { Code = material.code, Value = material });
            cmbMaterial.Properties.Items.Clear();
            foreach (MaterialDataInfo item in list)
                cmbMaterial.Properties.Items.Add(item);
        }

        private void IniSupplierCombox()
        {
            if (m_SupplierArr == null || m_SupplierArr.Length == 0)
                return;
            var list = new List<SupplierDataInfo>();
            list.Add(new SupplierDataInfo { Code ="", Value = null });
            foreach (supplierWS supplier in m_SupplierArr)
                list.Add(new SupplierDataInfo { Code = supplier.code, Value = supplier });
            cmbSupplier.Properties.Items.Clear();
            foreach (SupplierDataInfo item in list)
                cmbSupplier.Properties.Items.Add(item);
        }

        private void Search()
        {
            purchaseOrderWS[] purchaseOrderArr = null;
            try
            {
                using (LTCardAPIServiceClient client = new LTCardAPIServiceClient())
                {
                    purchaseOrderArr = client.getPurchaseOrders(DateTime.MinValue, DateTime.MaxValue,
                        m_CurrentOrderCode, m_CurrentMaterialId, m_CurrentSupplierId);
                }
            }
            catch (System.ServiceModel.EndpointNotFoundException ex)
            {
                LogHelper.error("网络通讯异常：" + ex.Message);
                MessageBox.Show("网络通讯异常,详细信息请参考日志文件!");
                return;
            }
            catch (TimeoutException ex)
            {
                LogHelper.error("网络通讯超时：" + ex.Message);
                MessageBox.Show("网络通讯超时,详细信息请参考日志文件!");
                return;
            }
            catch (Exception ex)
            {
                LogHelper.error("获取采购订单异常：" + ex.Message);
                MessageBox.Show("获取采购订单异常,详细信息请参考日志文件!");
                return;
            }
            m_BindDT.Rows.Clear();
            this.gridOrder.DataSource = m_BindDT;
            if (purchaseOrderArr == null || purchaseOrderArr.Length == 0)
                return;
            BindGrid(purchaseOrderArr);
        }

        private void BindGrid(purchaseOrderWS[] purchaseOrderArr)
        {
            m_BindDT.Rows.Clear();
            try
            {
                //按订单时间排序的，最近的订单在最前面
                var query = from temp in purchaseOrderArr
                            orderby temp.deliveryDate descending
                            select temp;
                foreach (purchaseOrderWS purchaseOrder in query)
                {
                    m_BindDT.Rows.Add(purchaseOrder.id,
                       purchaseOrder.material == null ? "" : purchaseOrder.material.name,
                       purchaseOrder.supplier == null ? "" : purchaseOrder.supplier.name,
                       purchaseOrder.place == null ? "" : purchaseOrder.place.name,
                       purchaseOrder.code,
                       purchaseOrder.orderQuantity.ToString("0.00"), purchaseOrder.receQuantity.ToString("0.00"), purchaseOrder.deliveryDate.ToString("yyyy-MM-dd"));
                    if (!m_PurchaseOrderDic.ContainsKey(purchaseOrder.id))
                        m_PurchaseOrderDic.Add(purchaseOrder.id, purchaseOrder);
                }
                gridOrder.DataSource = m_BindDT;
            }
            catch (Exception ex)
            {
                LogHelper.error("绑定订单列表错误：" + ex.Message);
            }
        }
        private MaterialDataInfo FindMaterialDataInfoByKey(ComboBoxEdit cmb, string key)
        {
            foreach (MaterialDataInfo info in cmb.Properties.Items)
            {
                if (info.Code == key)
                {
                    return info;
                }
            }
            return null;
        }

        private SupplierDataInfo FindSupplierDataInfoByKey(ComboBoxEdit cmb, string key)
        {
            foreach (SupplierDataInfo info in cmb.Properties.Items)
            {
                if (info.Code == key)
                {
                    return info;
                }
            }
            return null;
        }
        #endregion

        private void btnSearch_Click(object sender, EventArgs e)
        {
            Search();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            m_SelectPurchaseOrder = null;
            if (gridOrder.Rows.Count == 0)
            {
                MessageBox.Show("该查询条件下无采购订单，请修改查询！");
                return;
            }
            if (gridOrder.CurrentRow.Index < 0)
            {
                MessageBox.Show("请选择一条采购订单！");
                return;
            }
            long orderId = Convert.ToInt64(gridOrder.CurrentRow.Cells["idColumn"].Value);
            m_SelectPurchaseOrder = m_PurchaseOrderDic[orderId];
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.Close();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Close();
        }

        private void cmbMaterial_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbMaterial.SelectedItem == null || cmbMaterial.SelectedItem == "")
                m_CurrentMaterialId = 0;
            else
            {
                if (cmbMaterial.SelectedItem is MaterialDataInfo 
                    && ((MaterialDataInfo)cmbMaterial.SelectedItem).Value != null)
                    m_CurrentMaterialId = ((MaterialDataInfo)cmbMaterial.SelectedItem).Value.id;
                else
                    m_CurrentMaterialId = 0;
            }
        }

        private void cmbSupplier_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbSupplier.SelectedItem == null || cmbSupplier.SelectedItem == "")
                m_CurrentSupplierId = 0;
            else
            {
                if (cmbSupplier.SelectedItem is SupplierDataInfo 
                    && ((SupplierDataInfo)cmbSupplier.SelectedItem).Value != null)
                    m_CurrentSupplierId = ((SupplierDataInfo)cmbSupplier.SelectedItem).Value.id;
                else
                     m_CurrentSupplierId = 0;
            }
        }

        private void cmbMaterial_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 13)
                return;
            string code = cmbMaterial.Text.Trim();
            if (!string.IsNullOrEmpty(code))
                cmbMaterial.SelectedItem = FindMaterialDataInfoByKey(cmbMaterial, code);
            this.btnSearch_Click(null, null);
        }

        private void cmbSupplier_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 13)
                return;
            string code = cmbSupplier.Text.Trim();
            if (!string.IsNullOrEmpty(code))
                cmbSupplier.SelectedItem = FindSupplierDataInfoByKey(cmbSupplier, code);
            this.btnSearch_Click(null, null);
        }

        private void gridOrder_DoubleClick(object sender, EventArgs e)
        {
            m_SelectPurchaseOrder = null;
            if (gridOrder.Rows.Count == 0)
                return;
            if (gridOrder.CurrentRow.Index < 0)
                return;
            long orderId = Convert.ToInt64(gridOrder.CurrentRow.Cells["idColumn"].Value);
            m_SelectPurchaseOrder = m_PurchaseOrderDic[orderId];
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.Close();
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            this.cmbMaterial.Text = "";
            this.cmbSupplier.Text = "";
            this.txtOrderCode.Text = "";
            this.btnSearch_Click(null, null);
        }
    }
}
